//
//  ParserTCL.java
//  TopoManipApplet
//
//  Created by Thibaud PIQUET on 23/03/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
package src.convertisseur;

import java.util.*;
import java.io.*;
import org.jdom.*;

/**
 *
 * @author Thibaud PIQUET
 *
 * Version 1.1 - Ksoobrayen : Evolutions vers un fichier graphML --> Le 03 mars 2011
 */
public class ParserTCL implements Runnable {

    File ftp; // File to Parse
    File fileOut; // File to create
    Reader fr; // File Reader
    BufferedReader br; // Buffer Reader
    String line;
    String chaine;
    String[] res;
    String[] keyGraphNode = {"name", "status", "switch"};
    String[] keyGraphEdge = {"status", "bandwidth", "delay", "linkType", "queue"};
    String KEY = "key";
    String DATA = "data";

    public ParserTCL(File file, File fileOUT) throws IOException {
        this.ftp = file;
        this.fileOut = fileOUT;
        this.fr = new FileReader(this.ftp);
        this.br = new BufferedReader(this.fr);
    }

    public void run() {
        try {
            this.parseToXML();
        } catch (Exception e) {
            e.printStackTrace();
            Resume result = Resume.getInstance();
            result.add("ParserTCL", "procedure run had some problems : " + e);
        }
    }

    public void parseToXML() throws IOException {

        // <graphml xmlns="http://graphml.graphdrawing.org/xmlns">
        // <graph edgedefault="undirected">

        Element graphml = new Element("graphml");
        Namespace nsGraphml = Namespace.getNamespace("http://graphml.graphdrawing.org/xmlns");
        graphml.setNamespace(nsGraphml);


        Element graph = new Element("graph");
        Attribute edgedefault = new Attribute("edgedefault", "undirected");
        graph.setAttribute(edgedefault);


        Element domain = new Element("domain");
        Element information = new Element("information");
        Element topology = new Element("topology");
        Element igp = new Element("igp");
        Element nodes = new Element("nodes");
        Element links = new Element("links");
        Element igpLinks = new Element("links");

        Attribute nodeData;


        org.jdom.Document document = new Document(graphml);

        Resume result = Resume.getInstance();

        try {
            line = this.br.readLine();

            Element title = new Element("title");
            Element date = new Element("date");
            Element author = new Element("author");
            Element description = new Element("description");
            Date today = new Date();
            String day = "";
            String month = "";

            title.setText(fileOut.getName());
            if (today.getDate() < 10) {
                day = "0" + today.getDate();
            } else {
                day = today.getDate() + "";
            }
            if ((today.getMonth() + 1) < 10) {
                month = "0" + (today.getMonth() + 1);
            } else {
                month = (today.getMonth() + 1) + "";
            }
            date.setText((today.getYear() + 1900) + "-" + month + "-" + day);
            author.setText("File Generator");
            description.setText("File generated by ParserTCL from this jApplet");

            information.addContent(title);
            information.addContent(date);
            information.addContent(author);
            information.addContent(description);


            while (line != null) {
                if (line != null) {

                    if (line.contains("#")) {
                        chaine = "";
                        // it's commentary
                    } else if (line.startsWith("set")) {
                        if (line.contains("Simulator")) {
                            chaine = "";
                            // do nothing
                        } else if (line.contains("node")) {
                            chaine = "Node declaration : ";
                            res = line.split(" ");
                            // node id	res[1]

                            Element node = new Element("node");
                            Attribute id = new Attribute("id", res[1]);
                            Element nameNode = Utils.getNameNode("name", res[1]);


                            //Element switchNode = new Element("switch");
                            //switchNode.setText("false");

                            Element switchNode = Utils.getNameNode("switch", "false");

                            //Element statusNode = new Element("status");
                            //statusNode.setText("UP");

                            Element statusNode = Utils.getNameNode("status", "UP");


                            node.setAttribute(id);
                            node.addContent(nameNode);
                            node.addContent(statusNode);
                            node.addContent(switchNode);
                            nodes.addContent(node);
                        }
                    } else if (line.contains("$ns")) {
                        chaine = "Link declaration : ";
                        res = line.split(" ");
                        // $ns		res[0]
                        // link type	res[1]

                        if ((res[1].equals("simplex-link")) || (res[1].equals("duplex-link")) || (res[1].equals("duplex-link-op"))) { // normal link
                            // node source	res[2]
                            // node target	res[3]
                            // bandwidth	res[4]
                            // delay	res[5]
                            // queue	res[6]

                            Element link = new Element("edge");
                            Attribute idLink = new Attribute("id", res[2].substring(1) + res[3].substring(1));

                            //Element source = new Element("source");
                            Attribute srcNode = new Attribute("source", res[2].substring(1));

                            //Element target = new Element("target");
                            Attribute tgtNode = new Attribute("target", res[3].substring(1));

                            Element statusLink = Utils.getNameNode("status", "UP");


                            //Element bandwidth = new Element("bandwidth");
                            Element bandwidth = new Element(DATA);
                            nodeData = new Attribute(KEY, "bandwidth");
                            bandwidth.setAttribute(nodeData);
                            if (res[4].contains("Gb")) {
                                bandwidth.setText(res[4].replace("Gb", "000000000"));
                            } else if (res[4].contains("Mb")) {
                                bandwidth.setText(res[4].replace("Mb", "000000"));
                            } else {
                                bandwidth.setText(res[4]);
                            }

                            //Element delay = new Element("delay");
                            Element delay = new Element(DATA);
                            nodeData = new Attribute(KEY, "delay");
                            delay.setAttribute(nodeData);
                            if (res[5].contains("ms")) {
                                delay.setText(res[5].replace("ms", ""));
                            } else if (res[5].contains("s")) {
                                delay.setText((Integer.parseInt(res[5].replace("s", "")) / 1000) + "");
                            } else {
                                delay.setText(res[5]);
                            }

                            if (res.length == 7) {
                                //Element queue = new Element("queue");
                                //queue.setText(res[6]);
                                link.addContent(Utils.getNameNode("queue", res[6]));

                            }

                            //Element linkType = new Element("linkType");
                            //Attribute type1 = new Attribute("type1",res[1]);
                            Element linkType = new Element(DATA);
                            nodeData = new Attribute(KEY, "linkType");
                            linkType.setAttribute(nodeData);
                            Attribute type1 = new Attribute("type1", res[1]);

                            //source.setAttribute(srcNode);
                            //target.setAttribute(tgtNode);
                            linkType.setAttribute(type1);
                            link.setAttribute(idLink);
                            link.setAttribute(srcNode);
                            link.setAttribute(tgtNode);

                            //link.addContent(source);
                            //link.addContent(target);
                            link.addContent(statusLink);
                            link.addContent(bandwidth);
                            link.addContent(delay);

                            link.addContent(linkType);

                            links.addContent(link);
                        } else if (res[1].equals("cost")) { // igp cost
                            // node source res[2]
                            // node target res[3]
                            // cost res[4]

                            Element link = new Element("link");
                            Attribute idLink = new Attribute("id", res[2].substring(1) + res[3].substring(1));

                            //Element source = new Element("source");
                            Attribute srcNode = new Attribute("source", res[2].substring(1));

                            //Element target = new Element("target");
                            Attribute tgtNode = new Attribute("target", res[3].substring(1));

                            Element cost = Utils.getNameNode("cost", res[4]);

                            link.setAttribute(idLink);
                            link.setAttribute(srcNode);
                            link.setAttribute(tgtNode);
                            //source.setAttribute(srcNode);
                            //target.setAttribute(tgtNode);

                            //link.addContent(source);
                            //link.addContent(target);
                            link.addContent(cost);

                            igpLinks.addContent(link);
                        } else {
                        }
                    }
                }
                line = this.br.readLine();
            }
            br.close();
            fr.close();

            for (int i = 0; i < keyGraphNode.length; i++) {
                topology.addContent(Utils.getKeyGraph(i, keyGraphNode, "node"));

            }

            for (int i = 0; i < keyGraphEdge.length; i++) {
                topology.addContent(Utils.getKeyGraph(i, keyGraphEdge, "edge"));

            }


            topology.addContent(nodes);
            topology.addContent(links);

            List igpLinkslist = igpLinks.getChildren();
            if (igpLinkslist.isEmpty() == false) {
                igp.addContent(igpLinks);
            }

            domain.addContent(information);
            domain.addContent(topology);

            if (igpLinkslist.isEmpty() == false) {
                domain.addContent(igp);
            }

            graph.addContent(domain);
            graphml.addContent(graph);

            org.jdom.output.XMLOutputter sortie = new org.jdom.output.XMLOutputter(org.jdom.output.Format.getPrettyFormat());
            sortie.output(document, new FileOutputStream(fileOut.getAbsolutePath()));

            result.add("ParserTCL", "Import succeeded");

        } catch (Exception e) {
            e.printStackTrace();
            result.add("ParserTCL", "Import had problems " + e);
        }
    }
}
